package com.cn.wanxi.util;

import java.sql.*;
import java.util.List;

public class JDBC {
    //    1.加载驱动
//    2.得到链接
//    3.编译sql语句
    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    private JDBC() {
    }

//    private static Connection connection = null;

    private static Connection getConnection() {
        Connection connection=null;
//        String url = "jdbc:mysql://localhost:3306/canyin04";
        String url = "jdbc:mysql://121.199.55.96:3306/canyin04";
        String user = "canyin04";//用户名
        String pass = "123456";//密码
        if (connection == null) {
            synchronized (JDBC.class) {
                if (connection == null) {
                    try {
                        connection = DriverManager.getConnection(url, user, pass);
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return connection;
    }

    public static ResultSet query(String sql, List<Object> data) {
//        getConnection();
        try {
//            编译sql语句
            PreparedStatement preparedStatement = getConnection().prepareStatement(sql);
            if (data != null)
                for (int i = 0; i < data.size(); i++) {
                    preparedStatement.setObject(i + 1, data.get(i));
                }
//            执行sql语句
            ResultSet resultSet = preparedStatement.executeQuery();
//            解析结果ResultSet集
            return resultSet;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static int update(String sql, List<Object> data) {
//        getConnection();
        try {
//            编译sql语句
            PreparedStatement preparedStatement = getConnection().prepareStatement(sql);
            for (int i = 0; i < data.size(); i++) {
                preparedStatement.setObject(i + 1, data.get(i));
            }
            return preparedStatement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }


}
